//
//  BusiNetworkManager.m
//  NetworkDemo
//
//  Created by 万孟超 on 2022/1/10.
//

#import "BusiNetworkManager.h"
#import "NSObject+AutoCancelCategory.h"

#define NetworkManager [NetworkManager defaultManager]

@implementation BusiNetworkManager

/// 网络请求入口
/// @param target 代理
/// @param request 请求体
/// @param completeBlock 成功回调
/// @param errorBlock 失败回调
+ (NetworkEngine *)queryNetworkWithEngineTarget:(NSObject * _Nullable)target
                                        request:(NetworkBaseRequest *)request
                                  completeBlock:(nullable CompletionBlock)completeBlock
                                     errorBlock:(nullable ErrorBlock)errorBlock {
    NetworkEngine *networkEngine = [[NetworkEngine alloc] initWithRequestMethod:request.method];
    __weak typeof(target) weakTarget = target;
    id<NetworkProgressDelegate> delegate = (id)weakTarget;
    if (target) {
        [target.networkAutoCancel addEngine:networkEngine];
    }
    [NetworkManager POSTWithRequest:request enginePoint:networkEngine.enginePoint progressBlock:^(NSProgress * _Nullable progress) {
        if ([delegate respondsToSelector:@selector(network:progress:)]) {
            [delegate network:request progress:progress];
        }
    } successBlock:^(id  _Nullable result) {
        if (weakTarget) {
            [weakTarget.networkAutoCancel removeEngine:networkEngine];
        }
        if (completeBlock) {
            completeBlock(result);
        }
    } errorBlock:^(NSError * _Nullable error) {
        if (weakTarget) {
            [weakTarget.networkAutoCancel removeEngine:networkEngine];
        }
        if (errorBlock) {
            errorBlock(error);
        }
    }];
    return networkEngine;
}

@end
